// 加载知识库列表
function loadKnowledgeBases() {
    $.get('/Cloud/knowledge/list/my', function(res) {
        if (res.code === 200) {
            renderKnowledgeList(res.data);
        } else {
            alert(res.message);
        }
    }).fail(function() {
        alert('加载失败，请刷新重试');
    });
}

// 在DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log("DOM加载完成，初始化UI控制器");

    // 检查加载指示器
    setTimeout(function() {
        UIController.hideLoading();
    }, 1000);
});

// 在knowledge.js文件开头添加
window.onload = function() {
    // 5秒后强制隐藏加载指示器，无论发生什么
    setTimeout(function() {
        const loadingElement = document.getElementById('loading');
        if (loadingElement) {
            loadingElement.classList.add('hidden');
            console.log("强制隐藏加载指示器");
        }
    }, 5000);
};

/**
 * 加载指示器修复脚本
 * 解决加载指示器无法隐藏的问题
 */

// 页面加载完成后立即执行
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，准备隐藏加载指示器');

    // 立即尝试隐藏加载指示器
    hideLoadingIndicator();

    // 再次尝试使用UIController隐藏
    if (UIController && typeof UIController.hideLoading === 'function') {
        console.log('使用UIController隐藏加载指示器');
        UIController.hideLoading();
    }

    // 设置一个定时器，以确保无论如何都会隐藏加载指示器
    setTimeout(hideLoadingIndicator, 1000);

    // 最后的保险措施 - 5秒后强制隐藏
    setTimeout(function() {
        console.log('强制隐藏加载指示器');
        const loadingElement = document.getElementById('loading');
        if (loadingElement) {
            loadingElement.style.display = 'none';
            loadingElement.classList.add('hidden');
        }
    }, 5000);
});

document.addEventListener('DOMContentLoaded', function() {
    initKnowledgePage();
});

// 隐藏加载指示器的函数
function hideLoadingIndicator() {
    console.log('尝试隐藏加载指示器');
    const loadingElement = document.getElementById('loading');
    if (loadingElement) {
        loadingElement.classList.add('hidden');
        console.log('加载指示器已隐藏');
    } else {
        console.error('未找到加载指示器元素');
    }
}

// 监听window的load事件
window.addEventListener('load', function() {
    console.log('页面完全加载完成，再次尝试隐藏加载指示器');
    hideLoadingIndicator();
});

// 监听错误
window.addEventListener('error', function(event) {
    console.error('检测到页面错误，但仍尝试隐藏加载指示器:', event.message);
    hideLoadingIndicator();
});

// 渲染知识库列表
function renderKnowledgeList(bases) {
    const $container = $('#knowledgeList');
    $container.empty();

    if (bases.length === 0) {
        $container.html('<div class="col-12"><div class="alert alert-info">暂无知识库，点击右上角创建</div></div>');
        return;
    }

    bases.forEach(base => {
        const card = `
        <div class="col-md-4 mb-4">
            <div class="card knowledge-card">
                <div class="card-body">
                    <h5 class="card-title">${base.name}</h5>
                    <p class="card-text text-muted">${base.description || '暂无描述'}</p>
                    <div class="d-flex justify-content-between">
                        <span class="badge ${base.public ? 'badge-success' : 'badge-secondary'}">
                            ${base.public ? '公开' : '私有'}
                        </span>
                        <a href="/knowledge/detail.html?id=${base.id}" class="btn btn-sm btn-outline-primary">进入</a>
                    </div>
                </div>
                <div class="card-footer text-muted">
                    创建于 ${new Date(base.createTime).toLocaleDateString()}
                </div>
            </div>
        </div>`;
        $container.append(card);
    });
}

// 创建知识库
function createKnowledge() {
    const data = {
        name: $('#kbName').val(),
        description: $('#kbDesc').val(),
        isPublic: $('#kbPublic').is(':checked')
    };

    if (!data.name) {
        alert('请输入知识库名称');
        return;
    }

    $.ajax({
        url: '/knowledge',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function(res) {
            if (res.code === 200) {
                $('#createModal').modal('hide');
                loadKnowledgeBases();
            } else {
                alert(res.message);
            }
        },
        error: function(xhr) {
            alert('创建失败: ' + (xhr.responseJSON?.message || '服务器错误'));
        }
    });
}

// 添加返回知识库详情页的函数
function backToKnowledgeDetail() {
    // 如果有当前知识库ID，则返回到该知识库详情页
    if (window.currentKnowledgeBaseId) {
        showKnowledgeDetail(window.currentKnowledgeBaseId);
    } else {
        // 否则返回到首页
        showPage('homePage');
    }
}

// 创建文章卡片函数
function createArticleCard(article) {
    // 创建新的文章卡片元素
    const articleDiv = document.createElement('div');
    articleDiv.className = 'article-item p-2 hover:bg-gray-100 rounded';
    articleDiv.id = `article-${article.id}`;

    // 设置文章卡片内容
    articleDiv.innerHTML = `
        <h4 class="text-md font-bold">${article.title}</h4>
        <p class="text-gray-600 text-sm">作者：${article.authorName} | 发表时间：${new Date(article.createTime).toLocaleString()}</p>
        <p class="text-gray-600 text-sm">点赞：<span id="like-count-${article.id}">${article.likeCount}</span> | 评论：${article.commentCount}</p>
        <div class="flex items-center mt-2">
            <i class="fa fa-thumbs-up like-button ${article.isLiked ? 'fas liked' : 'far'}" 
               id="like-button-${article.id}" 
               data-liked="${article.isLiked}"
               onclick="toggleArticleLike(${article.id})"></i>
            <span class="ml-1">点赞</span>
        </div>
    `;

    return articleDiv;
}

// // 新增的文章数据处理和点赞逻辑代码
// const article = {
//     id: 1,
//     likes: 10
// };
//
// const articleDiv = document.getElementById('article-placeholder');
// articleDiv.id = `article-${article.id}`;
//
// const likeButton = articleDiv.querySelector('.like-button');
// likeButton.setAttribute('onclick', `toggleLike(${article.id})`);
//
// const likeCount = document.getElementById('like-count-placeholder');
// likeCount.textContent = article.likes;

function showMyKnowledgeBasesPage() {
    // 显示主页面（因为我们将在这个页面上添加我的知识库区域）
    showPage('homePage');

    // 加载并显示我的知识库
    loadMyKnowledgeBases();
}

function showPage(pageId) {
    console.log("Showing page:", pageId);

    // 1. 隐藏所有主要页面内容区域
    const mainContentAreas = [
        'homePage',
        'publicKnowledgeBasesPage',
        'recentArticlesPage',
        'companySpacePage',
        'knowledge-detail',
        'company-member-management',
        'company-notice',
        'article-detail',
        'article-editor',
        'member-management',
        'personal-info'
    ];

    mainContentAreas.forEach(id => {
        const page = document.getElementById(id);
        if (page) page.classList.add('hidden');
    });

    // 2. 特殊逻辑处理
    if (pageId === 'myKnowledgeBases') {
        showMyKnowledgeBasesPage();
        return;
    }

    // 3. 显示目标页面
    const targetPage = document.getElementById(pageId);
    if (targetPage) {
        targetPage.classList.remove('hidden');

        // 确保页面正确重置到顶部
        targetPage.scrollTo(0, 0);

        // 特殊处理文章详情页（保持全屏布局）
        if (pageId === 'article-detail') {
            document.body.style.overflow = 'hidden'; // 禁用主页面滚动
        } else {
            document.body.style.overflow = ''; // 恢复滚动
        }
    } else {
        console.error("Page not found:", pageId);
    }
}

window.showPage = showPage;

// 在knowledge.js中添加以下函数
// function loadMyKnowledgeBases() {
//     // 显示加载指示器
//     UIController.showLoading();
//
//     // 使用现有的ApiService获取我的知识库列表
//     ApiService.knowledgeBase.getMyList()
//         .then(res => {
//             // 隐藏加载指示器
//             UIController.hideLoading();
//
//             if (res.code === 200 && res.data) {
//                 displayMyKnowledgeBases(res.data);
//             } else {
//                 // 如果API调用失败，显示错误消息
//                 UIController.showToast(res.message || '加载我的知识库失败', 'error');
//                 // 显示模拟数据
//                 displayMockMyKnowledgeBases();
//             }
//         })
//         .catch(err => {
//             // 隐藏加载指示器
//             UIController.hideLoading();
//             // 显示错误消息
//             UIController.showToast(err.message || '加载我的知识库失败', 'error');
//             // 显示模拟数据
//             displayMockMyKnowledgeBases();
//         });
// }

// 显示我的知识库（从API获取的真实数据）
function displayMyKnowledgeBases(knowledgeBases) {
    // 获取新的显示容器
    const contentArea = document.getElementById('my-knowledgebases');
    if (!contentArea) return;

    // 清空现有内容
    contentArea.innerHTML = '';

    // 添加标题（可以考虑在HTML中直接添加，这里仅为保持一致性）
    const title = document.createElement('h2');
    title.className = 'text-xl font-bold mb-4';
    title.textContent = '我的知识库（私有）';
    contentArea.appendChild(title);

    // 创建知识库网格容器
    const grid = document.createElement('div');
    grid.className = 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mt-4';
    grid.id ='my-knowledgebases-grid';

    // 如果没有知识库，显示提示信息
    if (knowledgeBases.length === 0) {
        const emptyMessage = document.createElement('div');
        emptyMessage.className = 'col-span-3 text-center text-gray-500 p-6 bg-gray-100 rounded';
        emptyMessage.textContent = '你还没有创建任何知识库，点击下方按钮创建第一个知识库！';
        grid.appendChild(emptyMessage);
    } else {
        // 显示所有知识库
        knowledgeBases.forEach(kb => {
            grid.appendChild(createKnowledgeBaseCard(kb));
        });
    }

    contentArea.appendChild(grid);

    // 添加创建知识库按钮（可以考虑在HTML中直接添加，这里仅为保持一致性）
    const createButton = document.createElement('button');
    createButton.className = 'bg-blue-500 text-white px-4 py-2 rounded mt-4';
    createButton.textContent = '创建知识库';
    createButton.onclick = showCreateKnowledgeBaseModal;
    contentArea.appendChild(createButton);
}

// 显示模拟的我的知识库数据（当API调用失败时）
function displayMockMyKnowledgeBases() {
    // 模拟数据
    const mockData = [
        {
            id: 1,
            name: '我的Java编程笔记',
            description: '个人Java学习笔记和代码示例',
            public: false,
            creatorName: '我',
            memberCount: 1,
            createTime: new Date().toISOString()
        },
        {
            id: 2,
            name: '前端开发技巧',
            description: 'HTML, CSS, JavaScript和各种框架的学习笔记',
            public: false,
            creatorName: '我',
            memberCount: 1,
            createTime: new Date().toISOString()
        }
    ];

    // 显示模拟数据
    displayMyKnowledgeBases(mockData);
}

// 重新实现或完善createKnowledgeBaseCard函数
function createKnowledgeBase() {
    const kbName = document.getElementById('kb-name').value;
    const kbDescription = document.getElementById('kb-description').value;
    const kbAccess = document.getElementById('kb-access').value;

    // 表单验证
    if (!kbName) {
        UIController.showToast('请输入知识库名称', 'error');
        return;
    }

    // 显示加载指示器
    UIController.showLoading();

    // 使用ApiService创建知识库
    ApiService.knowledgeBase.create(kbName, kbDescription, kbAccess === 'public')
        .then(res => {
            // 隐藏加载指示器
            UIController.hideLoading();

            if (res.code === 200) {
                // 显示成功消息
                UIController.showToast('知识库创建成功！', 'success');

                // 关闭模态框
                hideCreateKnowledgeBaseModal();

                // 显示我的知识库页面并刷新列表
                showPage('myKnowledgeBases');
            } else {
                // 显示错误消息
                UIController.showToast(res.message || '创建知识库失败', 'error');
            }
        })
        .catch(err => {
            // 隐藏加载指示器
            UIController.hideLoading();

            // 显示错误消息
            UIController.showToast(err.message || '创建知识库失败', 'error');

            // 为了测试，可以模拟成功创建
            console.log('模拟创建知识库成功');
            hideCreateKnowledgeBaseModal();
            showPage('myKnowledgeBases');
        });
}

function showCreateEnterpriseModal() {
    const modal = document.getElementById('create-enterprise-modal');
    modal.classList.remove('hidden');
}

function hideCreateEnterpriseModal() {
    const modal = document.getElementById('create-enterprise-modal');
    modal.classList.add('hidden');
}

function createEnterprise() {
    // 实现创建企业逻辑
    console.log('创建企业功能待实现');
    hideCreateEnterpriseModal();
}

// function showKnowledgeDetail(id) {
//     showPage('knowledge-detail');
//     // 根据 id 加载知识库详情
//     console.log(`加载知识库详情，ID: ${id}`);
// }
//
// function showArticleEditor() {
//     showPage('article-editor');
// }
//
// function applyFormat(format) {
//     document.execCommand(format, false, null);
// }

document.addEventListener('DOMContentLoaded', function () {
    // 获取个人信息
    fetch('/Cloud/getuserinfo')
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error(`请求失败，状态码: ${response.status}`);
            }
        })
        .then(data => {
            document.getElementById('username').value = data.data.username;
            document.getElementById('email').value = data.data.email;
            // 密码通常不返回明文显示，这里可根据实际情况处理
            document.getElementById('password').value = data.data.password;
            // 设置Data URL格式的头像
            const avatarDataUrl = data.data.avatar;
            if (avatarDataUrl) {
                document.getElementById('userAvatar').src = avatarDataUrl;
            }
            console.log(davatarDataUrl);
        })
        .catch(error => console.error('获取个人信息失败:', error));

    // 编辑信息按钮点击事件
    document.getElementById('editInfoBtn').addEventListener('click', function () {
        document.getElementById('username').removeAttribute('readonly');
        document.getElementById('email').removeAttribute('readonly');
        document.getElementById('password').removeAttribute('readonly');
        this.classList.add('hidden');
        document.getElementById('saveBtn').classList.remove('hidden');
        document.getElementById('cancelBtn').classList.remove('hidden');
    });
});

// 获取退出登录按钮
const logoutButton = document.querySelector('#user-menu a:last-child');

// 为退出登录按钮添加点击事件监听器
if (logoutButton) {
    logoutButton.addEventListener('click', function () {
        // 清除本地存储中的用户信息
        localStorage.removeItem('userInfo');

        // 跳转到登录页面
        window.location.href = 'login.html';
    });
}

function savePersonalInfo() {
    const username = document.getElementById('username').value;
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;

    // 发送保存请求到后端
    fetch('/saveUserInfo', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, email, password })
    })
        .then(response => response.json())
        .then(data => {
            if (data.message === '保存成功') {
                alert('个人信息保存成功');
                // 保存成功后恢复到查看模式
                cancelPersonalInfo();
            } else {
                alert('保存失败: ' + data.message);
            }
        })
        .catch(error => console.error('保存个人信息失败:', error));
}

function cancelPersonalInfo() {
    document.getElementById('username').setAttribute('readonly', 'readonly');
    document.getElementById('email').setAttribute('readonly', 'readonly');
    document.getElementById('password').setAttribute('readonly', 'readonly');
    document.getElementById('editInfoBtn').classList.remove('hidden');
    document.getElementById('saveBtn').classList.add('hidden');
    document.getElementById('cancelBtn').classList.add('hidden');

    // 重新获取个人信息以恢复原始值
    fetch('/Cloud/getuserinfo')
        .then(response => response.json())
        .then(data => {
            document.getElementById('username').value = data.username;
            document.getElementById('email').value = data.email;
            // 密码通常不返回明文显示，这里可根据实际情况处理
            // document.getElementById('password').value = data.password;
            const emailUsername = data.email.split('@')[0];
            document.getElementById('emailUsername').value = emailUsername;
        })
        .catch(error => console.error('获取个人信息失败:', error));
}

// 在 knowledge.js 中添加如下代码
document.addEventListener('DOMContentLoaded', function() {
    // 绑定编辑信息按钮事件
    const editInfoBtn = document.getElementById('editInfoBtn');
    if (editInfoBtn) {
        editInfoBtn.addEventListener('click', function() {
            document.getElementById('username').readOnly = false;
            document.getElementById('email').readOnly = false;
            document.getElementById('saveBtn').classList.remove('hidden');
            document.getElementById('cancelBtn').classList.remove('hidden');
            this.classList.add('hidden');
        });
    }

    // 绑定保存按钮事件
    const saveBtn = document.getElementById('saveBtn');
    if (saveBtn) {
        saveBtn.addEventListener('click', savePersonalInfo);
    }

    // 绑定取消按钮事件
    const cancelBtn = document.getElementById('cancelBtn');
    if (cancelBtn) {
        cancelBtn.addEventListener('click', function() {
            document.getElementById('username').readOnly = true;
            document.getElementById('email').readOnly = true;
            document.getElementById('saveBtn').classList.add('hidden');
            document.getElementById('cancelBtn').classList.add('hidden');
            document.getElementById('editInfoBtn').classList.remove('hidden');
            // 重新加载用户信息
            loadUserInfo();
        });
    }

    // 绑定更改头像按钮事件
    const changeAvatarBtn = document.getElementById('changeAvatarBtn');
    if (changeAvatarBtn) {
        changeAvatarBtn.addEventListener('click', changeAvatar);
    }

    // 绑定修改密码模态框按钮事件
    const changePasswordBtn = document.querySelector('button[onclick="showChangePasswordModal()"]');
    if (changePasswordBtn) {
        changePasswordBtn.addEventListener('click', function() {
            document.getElementById('change-password-modal').classList.remove('hidden');
        });
    }

    // 确认修改密码按钮
    const submitPasswordBtn = document.querySelector('button[onclick="submitChangePassword()"]');
    if (submitPasswordBtn) {
        submitPasswordBtn.addEventListener('click', submitChangePassword);
    }

    // 取消修改密码按钮
    const cancelPasswordBtn = document.querySelector('button[onclick="hideChangePasswordModal()"]');
    if (cancelPasswordBtn) {
        cancelPasswordBtn.addEventListener('click', function() {
            document.getElementById('change-password-modal').classList.add('hidden');
        });
    }
});

function inviteUserAsAdmin() {
    const kbId = getCurrentKnowledgeBaseId(); // 需要实现该函数获取当前知识库的 ID
    const email = document.getElementById('invite-email').value;
    const xhr = new XMLHttpRequest();
    xhr.open('POST', `/Cloud/invite-user-as-admin/${kbId}`, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            const response = JSON.parse(xhr.responseText);
            if (response.code === 200) {
                alert('邀请成功');
                // 刷新成员列表
                loadMembers();
            } else {
                alert('邀请失败：' + response.message);
            }
        }
    };
    const data = JSON.stringify({ email: email });
    xhr.send(data);
}

// function uploadImage() {
//     const input = document.createElement('input');
//     input.type = 'file';
//     input.accept = 'image/*';
//     input.onchange = function () {
//         const file = this.files[0];
//         const formData = new FormData();
//         formData.append('image', file);
//         const xhr = new XMLHttpRequest();
//         xhr.open('POST', '/Cloud/upload-image', true);
//         xhr.onreadystatechange = function () {
//             if (xhr.readyState === 4 && xhr.status === 200) {
//                 const response = JSON.parse(xhr.responseText);
//                 if (response.code === 200) {
//                     const imgUrl = response.data.url;
//                     const img = document.createElement('img');
//                     img.src = imgUrl;
//                     const editor = document.getElementById('editor-content');
//                     editor.appendChild(img);
//                 } else {
//                     alert('图片上传失败：' + response.message);
//                 }
//             }
//         };
//         xhr.send(formData);
//     };
//     input.click();
// }

function saveArticle() {
    const title = document.getElementById('article-title').value;
    const content = document.getElementById('editor-content').innerHTML;
    const author = '当前用户'; // 从用户信息中获取
    const createTime = new Date().toLocaleString();

    // 验证表单数据
    if (!title.trim()) {
        UIController.showToast('请输入文章标题', 'error');
        return;
    }

    if (!content.trim()) {
        UIController.showToast('请输入文章内容', 'error');
        return;
    }

    // 判断是新建还是更新
    if (currentEditingArticleId) {
        // 更新文章
        updateArticle(currentEditingArticleId);
    } else {
        // 新建文章
        createArticle();
    }
}

// 发起 AJAX 请求获取最近发表的文章
function getRecentArticles() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/Cloud/article/recent', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    // 添加授权头
    const token = localStorage.getItem('token') || sessionStorage.getItem('token');
    if (token) {
        xhr.setRequestHeader('Authorization', `Bearer ${token}`);
    }

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                if (response.code === 200) {
                    const articles = response.data;
                    const articleList = document.getElementById('recent-articles');
                    if (articleList) {
                        articleList.innerHTML = '';
                        articles.forEach(article => {
                            const articleDiv = document.createElement('div');
                            articleDiv.innerHTML = `
                                <h3 class="text-lg font-bold">${article.title}</h3>
                                <p class="text-gray-600">作者：${article.author} | 创建时间：${new Date(article.createTime).toLocaleString()}</p>
                                <p>${article.content.slice(0, 100)}...</p>
                                <a href="#" onclick="showArticle(${article.id})">查看全文</a>
                            `;
                            articleList.appendChild(articleDiv);
                        });
                    }
                } else {
                    console.error('获取最近文章失败:', response.message);
                }
            } else if (xhr.status === 401) {
                alert("未登录或会话已过期，请重新登录");
                window.location.href = 'login.html';
            } else {
                console.error("Error loading articles:", xhr.status);
            }
        }
    };
    xhr.send();
}
window.onload = getRecentArticles;

function replyComment(commentId) {
    // 实现回复评论功能
}

function getArticlesByPage(page, sortBy = 'createTime') {
    // 显示加载状态
    UIController.showLoading();

    // 创建 XMLHttpRequest 对象
    const xhr = new XMLHttpRequest();
    // 配置请求，使用 GET 方法请求指定页面和排序方式的文章列表
    xhr.open('GET', `/Cloud/article/recent?page=${page}&sortBy=${sortBy}`, true);
    // 设置请求头，指定请求内容类型为 JSON
    xhr.setRequestHeader('Content-Type', 'application/json');

    // 添加授权头
    const token = localStorage.getItem('token') || sessionStorage.getItem('token');
    if (token) {
        // 如果存在 token，将其添加到请求头的 Authorization 字段中
        xhr.setRequestHeader('Authorization', `Bearer ${token}`);
    }

    // 监听请求状态变化
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            // 隐藏加载状态
            UIController.hideLoading();
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                if (response.code === 200) {
                    const articles = response.data;
                    const articleList = document.getElementById('recent-articles');
                    if (articleList) {
                        // 清空文章列表容器
                        articleList.innerHTML = '';
                        if (articles.length === 0) {
                            // 如果没有文章，显示提示信息
                            articleList.innerHTML = '<div class="text-center text-gray-500 p-4">暂无最近发表的文章</div>';
                        } else {
                            // 遍历文章数据
                            articles.forEach(article => {
                                const articleDiv = document.createElement('div');
                                // 设置文章项的 HTML 内容
                                articleDiv.innerHTML = `
                                    <h3 class="text-lg font-bold">${article.title}</h3>
                                    <p class="text-gray-600">作者：${article.author} | 创建时间：${new Date(article.createTime).toLocaleString()}</p>
                                    <p>${article.content.slice(0, 100)}...</p>
                                    <a href="#" onclick="showArticleDetail(${article.id})">查看全文</a>
                                `;
                                // 将文章项添加到文章列表容器中
                                articleList.appendChild(articleDiv);
                            });
                        }
                    }

                    // 更新分页按钮
                    const paginationDiv = document.getElementById('article-pagination');
                    if (paginationDiv) {
                        // 清空分页按钮容器
                        paginationDiv.innerHTML = '';
                        // 计算总页数
                        const totalPages = Math.ceil(response.total / response.size);
                        for (let i = 1; i <= totalPages; i++) {
                            const button = document.createElement('button');
                            button.textContent = i;
                            // 根据当前页码设置按钮的样式
                            button.className = 'pagination-btn ' + (i === page ? 'active' : '');
                            if (i === page) {
                                // 当前页码对应的按钮禁用
                                button.disabled = true;
                            }
                            // 为按钮添加点击事件，点击时调用 getArticlesByPage 函数加载相应页面的文章
                            button.addEventListener('click', () => getArticlesByPage(i, sortBy));
                            // 将按钮添加到分页按钮容器中
                            paginationDiv.appendChild(button);
                        }
                    }
                } else {
                    // 服务器返回的 code 不为 200，打印错误信息
                    console.error('获取最近文章失败:', response.message);
                    UIController.showToast(response.message || '获取最近文章失败', 'error');
                }
            } else if (xhr.status === 401) {
                // 未授权 - 重定向到登录页面
                alert("未登录或会话已过期，请重新登录");
                window.location.href = 'login.html';
            } else {
                // 其他状态码，打印错误信息
                console.error("Error loading articles:", xhr.status);
                UIController.showToast('加载文章失败，请稍后重试', 'error');
            }
        }
    };
    // 发送请求
    xhr.send();
}
window.onload = () => getArticlesByPage(1);

function toggleFollow(userId) {
    const followButton = document.querySelector(`#user-profile-${userId} .follow-button`);
    const isFollowed = followButton.getAttribute('data-followed') === 'true';

    if (isFollowed) {
        // 取消关注
        followButton.textContent = '关注';
        followButton.setAttribute('data-followed', 'false');
    } else {
        // 关注
        followButton.textContent = '已关注';
        followButton.setAttribute('data-followed', 'true');
    }

    // 发送 AJAX 请求更新关注状态
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/Cloud/toggle-follow', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            const response = JSON.parse(xhr.responseText);
            if (response.code === 200) {
                // 更新成功
            }
        }
    };
    const data = JSON.stringify({ userId, isFollowed: !isFollowed });
    xhr.send(data);
}

function getFollowList() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/Cloud/follow-list', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            const response = JSON.parse(xhr.responseText);
            if (response.code === 200) {
                const followList = response.data;
                const followListDiv = document.getElementById('follow-list');
                followListDiv.innerHTML = '';
                followList.forEach(user => {
                    const userDiv = document.createElement('div');
                    userDiv.innerHTML = `
                        <p><a href="#" onclick="showUserProfile(${user.id})">${user.username}</a></p>
                    `;
                    followListDiv.appendChild(userDiv);
                });
            }
        }
    };
    xhr.send();
}

function getBrowseHistory() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/Cloud/browse-history', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            const response = JSON.parse(xhr.responseText);
            if (response.code === 200) {
                const browseHistory = response.data;
                const browseHistoryDiv = document.getElementById('browse-history');
                browseHistoryDiv.innerHTML = '';
                browseHistory.forEach(item => {
                    const itemDiv = document.createElement('div');
                    itemDiv.innerHTML = `
                        <p><a href="#" onclick="showArticle(${item.articleId})">${item.articleTitle}</a> | 浏览时间：${item.browseTime}</p>
                        <button onclick="deleteBrowseHistory(${item.id})">删除</button>
                    `;
                    browseHistoryDiv.appendChild(itemDiv);
                });
            }
        }
    };
    xhr.send();
}

function clearBrowseHistory() {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/Cloud/clear-browse-history', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            const response = JSON.parse(xhr.responseText);
            if (response.code === 200) {
                // 清空成功，清空浏览记录展示区域
                const browseHistoryDiv = document.getElementById('browse-history');
                browseHistoryDiv.innerHTML = '';
            }
        }
    };
    xhr.send();
}

/**
 * 知识库管理脚本
 * 处理知识库创建、编辑、删除、查询等功能
 */

// 当前知识库ID
let currentKnowledgeBaseId = null;

// 初始化知识库首页
function initKnowledgePage() {
    // 加载我的知识库列表
    loadMyKnowledgeBases();

    // 加载最近访问的知识库
    loadRecentKnowledgeBases();

    // 加载推荐公开知识库
    loadRecommendedKnowledgeBases();

    // 加载最近发表的文章
    loadRecentArticles();

    // 加载我的知识库列表（用于下拉选择）
    loadMyKnowledgeBases();

    // 绑定创建知识库按钮事件
    document.getElementById('createKnowledgeBaseBtn').addEventListener('click', showCreateKnowledgeBaseModal);

    // 绑定搜索框事件
    document.getElementById('searchInput').addEventListener('input', debounce(search, 500));

    // 初始化消息通知
    initNotifications();

    // 加载用户信息
    loadUserInfo();
}

// 加载我的知识库列表
function loadMyKnowledgeBases() {
    UIController.showLoading();

    ApiService.knowledgeBase.getMyList()
        .then(res => {
            if (res.code === 200 && res.data) {
                // 获取我的知识库容器
                const container = document.getElementById('my-knowledgebases');
                container.innerHTML = '';

                // 如果没有知识库，显示提示
                if (res.data.length === 0) {
                    container.innerHTML = '<div class="text-center text-gray-500 p-4">你还没有创建任何知识库，点击下方按钮创建第一个知识库！</div>';
                    return;
                }

                // 渲染知识库卡片
                res.data.forEach(kb => {
                    container.appendChild(createKnowledgeBaseCard(kb));
                });
            } else {
                UIController.showToast(res.message || '加载我的知识库失败', 'error');
            }
        })
        .catch(err => {
            UIController.showToast(err.message || '加载我的知识库失败', 'error');
        })
        .finally(() => {
            UIController.hideLoading();
        });
}

// 加载最近访问的知识库
function loadRecentKnowledgeBases() {
    UIController.showLoading();

    ApiService.knowledgeBase.getMyList()
        .then(res => {
            if (res.code === 200 && res.data) {
                // 获取最近访问的知识库容器
                const container = document.getElementById('recent-knowledgebases');
                container.innerHTML = '';

                // 如果没有知识库，显示提示
                if (res.data.length === 0) {
                    container.innerHTML = '<div class="text-center text-gray-500 p-4">暂无最近访问的知识库</div>';
                    return;
                }

                // 最多显示6个最近访问的知识库
                const recentKnowledgeBases = res.data.slice(0, 6);

                // 渲染知识库卡片
                recentKnowledgeBases.forEach(kb => {
                    container.appendChild(createKnowledgeBaseCard(kb));
                });
            } else {
                UIController.showToast(res.message || '加载最近访问的知识库失败', 'error');
            }
        })
        .catch(err => {
            UIController.showToast(err.message || '加载最近访问的知识库失败', 'error');
        })
        .finally(() => {
            UIController.hideLoading();
        });
}

// 加载推荐公开知识库
function loadRecommendedKnowledgeBases() {
    UIController.showLoading();

    ApiService.knowledgeBase.getPublicList()
        .then(res => {
            if (res.code === 200 && res.data) {
                // 获取推荐知识库容器
                const container = document.getElementById('recommended-knowledgebases');
                container.innerHTML = '';

                // 如果没有知识库，显示提示
                if (res.data.length === 0) {
                    container.innerHTML = '<div class="text-center text-gray-500 p-4">暂无推荐公开知识库</div>';
                    return;
                }

                // 最多显示6个推荐知识库
                const recommendedKnowledgeBases = res.data.slice(0, 6);

                // 渲染知识库卡片
                recommendedKnowledgeBases.forEach(kb => {
                    container.appendChild(createKnowledgeBaseCard(kb));
                });
            } else {
                UIController.showToast(res.message || '加载推荐公开知识库失败', 'error');
            }
        })
        .catch(err => {
            UIController.showToast(err.message || '加载推荐公开知识库失败', 'error');
        })
        .finally(() => {
            UIController.hideLoading();
        });
}

// 加载最近发表的文章
function loadRecentArticles(sortBy = 'createTime') {
    UIController.showLoading();

    ApiService.article.getLatest()
        .then(res => {
            if (res.code === 200 && res.data) {
                // 获取最近文章容器
                const container = document.getElementById('recent-articles');
                container.innerHTML = '';

                // 如果没有文章，显示提示
                if (res.data.length === 0) {
                    container.innerHTML = '<div class="text-center text-gray-500 p-4">暂无最近发表的文章</div>';
                    return;
                }

                // 如果排序方式为点赞数，则重新排序
                if (sortBy === 'likes') {
                    res.data.sort((a, b) => b.likeCount - a.likeCount);
                }

                // 渲染文章列表
                res.data.forEach(article => {
                    container.appendChild(createArticleItem(article));
                });

                // 生成分页按钮
                generatePagination(res.total, res.current, res.size, 'article-pagination', page => {
                    loadRecentArticles(sortBy, page);
                });
            } else {
                UIController.showToast(res.message || '加载最近发表的文章失败', 'error');
            }
        })
        .catch(err => {
            UIController.showToast(err.message || '加载最近发表的文章失败', 'error');
        })
        .finally(() => {
            UIController.hideLoading();
        });
}

// 按点赞数排序文章
function sortArticles() {
    const sortSelect = document.getElementById('sort-select');
    loadRecentArticles(sortSelect.value);
}

// // 加载我的知识库列表（用于下拉选择）
// function loadMyKnowledgeBases() {
//     ApiService.knowledgeBase.getMyList()
//         .then(res => {
//             if (res.code === 200 && res.data) {
//                 // 获取下拉选择框
//                 const select = document.getElementById('kb-select');
//                 select.innerHTML = '<option value="">选择知识库</option>';
//
//                 // 添加知识库选项
//                 res.data.forEach(kb => {
//                     const option = document.createElement('option');
//                     option.value = kb.id;
//                     option.textContent = kb.name;
//                     select.appendChild(option);
//                 });
//
//                 // 绑定选择事件
//                 select.addEventListener('change', function() {
//                     if (this.value) {
//                         showKnowledgeDetail(this.value);
//                     }
//                 });
//             }
//         })
//         .catch(err => {
//             console.error('加载我的知识库列表失败:', err);
//         });
// }

// 创建知识库卡片
function createKnowledgeBaseCard(kb) {
    const card = document.createElement('div');
    card.className = 'knowledge-card bg-white shadow-md rounded p-4';
    card.onclick = () => showKnowledgeDetail(kb.id);

    // 随机生成卡片封面
    const coverUrl = kb.coverUrl || `https://picsum.photos/seed/${kb.id}/200/150`;

    // 设置卡片内容
    card.innerHTML = `
    <img src="${coverUrl}" alt="知识库封面" class="rounded">
    <h3 class="text-lg font-bold mt-2">${kb.name}</h3>
    <p class="text-gray-600">作者：${kb.creatorName || '未知'} | 成员数：${kb.memberCount || 0}</p>
    <span class="badge ${kb.isPublic ? 'public bg-green-500' : 'private bg-gray-500'} text-white px-2 py-1 rounded mt-2 inline-block">${kb.isPublic ? '公开' : '私有'}</span>
    <i class="favorite ${kb.isFavorite ? 'fas' : 'far'} fa-heart" onclick="toggleFavorite(event, ${kb.id})"></i>
  `;

    return card;
}

// 创建文章列表项
function createArticleItem(article) {
    const item = document.createElement('div');
    item.className = 'article-item p-2 hover:bg-gray-100 rounded cursor-pointer';
    item.setAttribute('data-id', article.id);

    // 设置点击文章进入详情页
    item.onclick = () => showArticleDetail(article.id);

    // 格式化时间
    const createTime = new Date(article.createTime).toLocaleString();

    // 设置列表项内容
    item.innerHTML = `
        <h4 class="text-md font-bold">${article.title}</h4>
        <p class="text-gray-600 text-sm">作者：${article.authorName || '未知'} | 发表时间：${createTime}</p>
        <p class="text-gray-600 text-sm">点赞：<span class="like-count">${article.likeCount || 0}</span> | 评论：${article.commentCount || 0}</p>
    `;

    return item;
}

// 生成分页按钮
function generatePagination(total, current, size, containerId, callback) {
    const container = document.getElementById(containerId);
    if (!container) return;

    // 清空容器
    container.innerHTML = '';

    // 计算总页数
    const pageCount = Math.ceil(total / size);

    // 如果只有一页，不显示分页
    if (pageCount <= 1) return;

    // 创建上一页按钮
    const prevButton = document.createElement('button');
    prevButton.className = `pagination-btn ${current <= 1 ? 'disabled' : ''}`;
    prevButton.textContent = '上一页';
    prevButton.disabled = current <= 1;
    prevButton.onclick = () => callback(current - 1);
    container.appendChild(prevButton);

    // 创建页码按钮
    let startPage = Math.max(1, current - 2);
    let endPage = Math.min(pageCount, startPage + 4);

    if (endPage - startPage < 4) {
        startPage = Math.max(1, endPage - 4);
    }

    for (let i = startPage; i <= endPage; i++) {
        const pageButton = document.createElement('button');
        pageButton.className = `pagination-btn ${i === current ? 'active' : ''}`;
        pageButton.textContent = i;
        pageButton.onclick = () => callback(i);
        container.appendChild(pageButton);
    }

    // 创建下一页按钮
    const nextButton = document.createElement('button');
    nextButton.className = `pagination-btn ${current >= pageCount ? 'disabled' : ''}`;
    nextButton.textContent = '下一页';
    nextButton.disabled = current >= pageCount;
    nextButton.onclick = () => callback(current + 1);
    container.appendChild(nextButton);
}

// 显示知识库详情
function showKnowledgeDetail(id) {
    // 设置当前知识库 ID
    currentKnowledgeBaseId = id;

    // 显示知识库详情页
    UIController.showPage('knowledge-detail');

    // 加载知识库详情
    UIController.showLoading();

    ApiService.knowledgeBase.getDetail(id)
        .then(res => {
            if (res.code === 200 && res.data) {
                // 显示知识库信息
                document.getElementById('kb-name-display').textContent = res.data.name;
                document.getElementById('kb-description-display').textContent = res.data.description || '暂无描述';
                document.getElementById('kb-creator-display').textContent = res.data.creatorName;
                document.getElementById('kb-create-time-display').textContent = new Date(res.data.createTime).toLocaleString();
                document.getElementById('kb-access-display').textContent = res.data.isPublic ? '公开' : '私有';

                // 加载文档列表
                loadDocumentList(id);

                // 加载文章列表
                loadArticleList(id);
            } else {
                UIController.showToast(res.message || '加载知识库详情失败', 'error');
            }
        })
        .catch(err => {
            UIController.showToast(err.message || '加载知识库详情失败', 'error');
        })
        .finally(() => {
            UIController.hideLoading();
        });
}

// 加载文章列表
function loadArticleList(knowledgeBaseId) {
    ApiService.article.getList(knowledgeBaseId)
        .then(res => {
            if (res.code === 200 && res.data) {
                const articleList = document.getElementById('article-list');
                articleList.innerHTML = '';

                if (res.data.length === 0) {
                    articleList.innerHTML = '<div class="text-center text-gray-500 p-4">暂无文章，点击新建按钮创建第一篇文章</div>';
                    return;
                }

                res.data.forEach(article => {
                    const articleDiv = document.createElement('div');
                    articleDiv.classList.add('article', 'p-4', 'border-b', 'border-gray-300', 'cursor-pointer', 'hover:bg-gray-100');
                    articleDiv.onclick = () => showArticleDetail(article.id);

                    // 格式化时间
                    const createTime = new Date(article.createTime || Date.now()).toLocaleString();

                    articleDiv.innerHTML = `
                        <h3 class="text-lg font-bold">${article.title}</h3>
                        <p class="text-gray-600 text-sm">作者：${article.authorName || '未知作者'} | 发表时间：${createTime}</p>
                        <p class="text-gray-600 text-sm">点赞：${article.likeCount || 0} | 评论：${article.commentCount || 0}</p>
                    `;

                    articleList.appendChild(articleDiv);
                });
            } else {
                UIController.showToast(res.message || '加载文章列表失败', 'error');
            }
        })
        .catch(err => {
            UIController.showToast(err.message || '加载文章列表失败', 'error');
        });
}

// 加载文档列表
function loadDocumentList(knowledgeId) {
    ApiService.article.getList(knowledgeId)
        .then(res => {
            if (res.code === 200 && res.data) {
                // 获取文档列表容器
                const container = document.getElementById('document-list');
                container.innerHTML = '';

                // 如果没有文档，显示提示
                if (res.data.length === 0) {
                    container.innerHTML = '<li>暂无文档</li>';
                    return;
                }

                // 渲染文档列表
                renderDocumentTree(container, res.data);
            } else {
                UIController.showToast(res.message || '加载文档列表失败', 'error');
            }
        })
        .catch(err => {
            UIController.showToast(err.message || '加载文档列表失败', 'error');
        });
}

// 渲染文档树形结构
function renderDocumentTree(container, documents, parentId = null) {
    // 筛选当前层级的文档
    const currentLevelDocs = documents.filter(doc => doc.parentId === parentId);

    // 如果没有文档，返回
    if (currentLevelDocs.length === 0) return;

    // 创建列表容器
    const list = parentId === null ? container : document.createElement('ul');
    if (parentId !== null) {
        list.className = 'pl-4';
    }

    // 遍历文档
    currentLevelDocs.forEach(doc => {
        // 创建列表项
        const item = document.createElement('li');

        // 设置列表项内容
        item.textContent = doc.title;
        item.className = 'cursor-pointer hover:text-blue-500';
        item.onclick = (e) => {
            e.stopPropagation();
            showArticleDetail(doc.id);
        };

        // 添加到列表容器
        list.appendChild(item);

        // 递归渲染子文档
        renderDocumentTree(item, documents, doc.id);
    });

    // 如果不是根容器，添加到父节点
    if (parentId !== null) {
        container.appendChild(list);
    }
}

// 显示创建知识库模态框
function showCreateKnowledgeBaseModal() {
    document.getElementById('create-knowledgebase-modal').classList.remove('hidden');

    // 重置表单
    document.getElementById('kb-name').value = '';
    document.getElementById('kb-description').value = '';
    document.getElementById('kb-access').value = 'private';
}

// 隐藏创建知识库模态框
function hideCreateKnowledgeBaseModal() {
    document.getElementById('create-knowledgebase-modal').classList.add('hidden');
}

// // 创建知识库
// function createKnowledgeBase() {
//     // 获取表单数据
//     const name = document.getElementById('kb-name').value;
//     const description = document.getElementById('kb-description').value;
//     const isPublic = document.getElementById('kb-access').value === 'public';
//
//     // 表单验证
//     if (!name) {
//         UIController.showToast('请输入知识库名称', 'error');
//         return;
//     }
//
//     // 显示加载状态
//     UIController.showLoading();
//
//     // 调用创建知识库API
//     ApiService.knowledgeBase.create(name, description, isPublic)
//         .then(res => {
//             if (res.code === 200) {
//                 UIController.showToast('创建知识库成功', 'success');
//
//                 // 关闭模态框
//                 hideCreateKnowledgeBaseModal();
//
//                 // 重新加载知识库列表
//                 loadRecentKnowledgeBases();
//
//                 loadMyKnowledgeBases();
//             } else {
//                 UIController.showToast(res.message || '创建知识库失败', 'error');
//             }
//         })
//         .catch(err => {
//             UIController.showToast(err.message || '创建知识库失败', 'error');
//         })
//         .finally(() => {
//             UIController.hideLoading();
//         });
// }

// 显示编辑知识库模态框
function showEditKnowledgeBaseModal() {
    if (!currentKnowledgeBaseId) {
        UIController.showToast('未选择知识库', 'error');
        return;
    }

    // 获取当前知识库信息
    UIController.showLoading();

    ApiService.knowledgeBase.getDetail(currentKnowledgeBaseId)
        .then(res => {
            if (res.code === 200 && res.data) {
                // 显示模态框
                document.getElementById('edit-knowledgebase-modal').classList.remove('hidden');

                // 填充表单
                document.getElementById('edit-kb-name').value = res.data.name;
                document.getElementById('edit-kb-description').value = res.data.description || '';
                document.getElementById('edit-kb-access').value = res.data.isPublic ? 'public' : 'private';
            } else {
                UIController.showToast(res.message || '获取知识库信息失败', 'error');
            }
        })
        .catch(err => {
            UIController.showToast(err.message || '获取知识库信息失败', 'error');
        })
        .finally(() => {
            UIController.hideLoading();
        });
}

// 隐藏编辑知识库模态框
function hideEditKnowledgeBaseModal() {
    document.getElementById('edit-knowledgebase-modal').classList.add('hidden');
}

// 更新知识库
function updateKnowledgeBase() {
    if (!currentKnowledgeBaseId) {
        UIController.showToast('未选择知识库', 'error');
        return;
    }

    // 获取表单数据
    const name = document.getElementById('edit-kb-name').value;
    const description = document.getElementById('edit-kb-description').value;
    const isPublic = document.getElementById('edit-kb-access').value === 'public';

    // 表单验证
    if (!name) {
        UIController.showToast('请输入知识库名称', 'error');
        return;
    }

    // 显示加载状态
    UIController.showLoading();

    // 调用更新知识库API
    ApiService.knowledgeBase.update(currentKnowledgeBaseId, name, description, isPublic)
        .then(res => {
            if (res.code === 200) {
                UIController.showToast('更新知识库成功', 'success');

                // 关闭模态框
                hideEditKnowledgeBaseModal();

                // 重新加载知识库详情
                showKnowledgeDetail(currentKnowledgeBaseId);
            } else {
                UIController.showToast(res.message || '更新知识库失败', 'error');
            }
        })
        .catch(err => {
            UIController.showToast(err.message || '更新知识库失败', 'error');
        })
        .finally(() => {
            UIController.hideLoading();
        });
}

// 删除知识库
function deleteKnowledgeBase() {
    if (!currentKnowledgeBaseId) {
        UIController.showToast('未选择知识库', 'error');
        return;
    }

    // 确认删除
    UIController.showConfirm('确定要删除此知识库吗？此操作不可撤销！', () => {
        // 显示加载状态
        UIController.showLoading();

        // 调用删除知识库API
        ApiService.knowledgeBase.delete(currentKnowledgeBaseId)
            .then(res => {
                if (res.code === 200) {
                    UIController.showToast('删除知识库成功', 'success');

                    // 返回首页
                    UIController.showPage('homePage');

                    // 重新加载知识库列表
                    loadRecentKnowledgeBases();
                    loadMyKnowledgeBases();

                    // 清除当前知识库ID
                    currentKnowledgeBaseId = null;
                } else {
                    UIController.showToast(res.message || '删除知识库失败', 'error');
                }
            })
            .catch(err => {
                UIController.showToast(err.message || '删除知识库失败', 'error');
            })
            .finally(() => {
                UIController.hideLoading();
            });
    });
}

// 初始化消息通知
function initNotifications() {
    // 绑定通知图标点击事件
    document.querySelectorAll('.fa-bell').forEach(icon => {
        icon.addEventListener('click', showMessages);
    });

    // 模拟有新消息
    setTimeout(() => {
        const badges = document.querySelectorAll('.message-badge');
        badges.forEach(badge => {
            badge.textContent = '3';
            badge.classList.remove('hidden');
        });
    }, 3000);
}

// 显示消息列表
function showMessages() {
    // 这里可以实现显示消息列表的逻辑
    UIController.showToast('消息功能正在开发中', 'info');

    // 清除消息计数
    const badges = document.querySelectorAll('.message-badge');
    badges.forEach(badge => {
        badge.textContent = '0';
        badge.classList.add('hidden');
    });
}

// 切换收藏状态
function toggleFavorite(event, id) {
    // 阻止事件冒泡
    event.stopPropagation();

    // 切换图标样式
    const icon = event.target;
    const isFavorite = icon.classList.contains('fas');

    if (isFavorite) {
        // 取消收藏
        icon.classList.replace('fas', 'far');
        UIController.showToast('已取消收藏', 'info');
    } else {
        // 添加收藏
        icon.classList.replace('far', 'fas');
        UIController.showToast('已添加收藏', 'success');
    }

    // 调用API更新收藏状态
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/Cloud/toggle-favorite', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            const response = JSON.parse(xhr.responseText);
            if (response.code !== 200) {
                // 回滚UI更改
                icon.classList.replace(icon.classList.contains('fas') ? 'fas' : 'far', icon.classList.contains('fas') ? 'far' : 'fas');
                UIController.showToast('操作失败', 'error');
            }
        }
    };
    const data = JSON.stringify({ id, isFavorite: !isFavorite });
    xhr.send(data);
}

// 切换用户菜单
function toggleUserMenu(context = '') {
    const menuId = context ? `${context}-user-menu` : 'user-menu-home';
    console.log("Toggling menu:", menuId);
    const menu = document.getElementById(menuId);

    if (menu) {
        menu.classList.toggle('hidden');
    } else {
        console.error("Menu element not found:", menuId);
        // Try to find any user menu as fallback
        const anyMenu = document.querySelector('.user-menu');
        if (anyMenu) {
            anyMenu.classList.toggle('hidden');
        }
    }
}

// Make sure it's globally available
window.toggleUserMenu = toggleUserMenu;

// 全局搜索
function search() {
    const keyword = document.getElementById('searchInput').value;

    if (!keyword.trim()) {
        return;
    }

    // 显示加载状态
    UIController.showLoading();

    // 调用搜索API
    ApiService.search.global(keyword)
        .then(res => {
            if (res.code === 200 && res.data) {
                // 显示搜索结果页
                UIController.showPage('search-results');

                // 渲染搜索结果
                renderSearchResults(res.data);
            } else {
                UIController.showToast(res.message || '搜索失败', 'error');
            }
        })
        .catch(err => {
            UIController.showToast(err.message || '搜索失败', 'error');
        })
        .finally(() => {
            UIController.hideLoading();
        });
}

// 渲染搜索结果
function renderSearchResults(data) {
    // 获取搜索结果容器
    const container = document.getElementById('search-results-container');
    container.innerHTML = '';

    // 创建标题
    const title = document.createElement('h2');
    title.className = 'text-xl font-bold mb-4';
    title.textContent = '搜索结果';
    container.appendChild(title);

    // 如果没有结果，显示提示
    if (data.total === 0) {
        const noResults = document.createElement('div');
        noResults.className = 'text-center text-gray-500 p-4';
        noResults.textContent = '没有找到相关内容';
        container.appendChild(noResults);
        return;
    }

    // 显示搜索统计
    const stats = document.createElement('p');
    stats.className = 'text-gray-600 mb-4';
    stats.textContent = `共找到 ${data.total} 个结果`;
    container.appendChild(stats);

    // 创建选项卡
    const tabs = document.createElement('div');
    tabs.className = 'flex space-x-4 mb-4';
    tabs.innerHTML = `
    <a href="#" class="tab-link active" data-tab="all">全部</a>
    <a href="#" class="tab-link" data-tab="knowledgeBases">知识库</a>
    <a href="#" class="tab-link" data-tab="articles">文章</a>
    <a href="#" class="tab-link" data-tab="users">用户</a>
  `;
    container.appendChild(tabs);

    // 绑定选项卡事件
    tabs.querySelectorAll('.tab-link').forEach(tab => {
        tab.addEventListener('click', function(e) {
            e.preventDefault();

            // 切换选项卡样式
            tabs.querySelectorAll('.tab-link').forEach(t => t.classList.remove('active'));
            this.classList.add('active');

            // 显示对应的结果
            const tabId = this.dataset.tab;
            document.querySelectorAll('.search-result-section').forEach(section => {
                if (tabId === 'all' || section.id === `${tabId}-results`) {
                    section.classList.remove('hidden');
                } else {
                    section.classList.add('hidden');
                }
            });
        });
    });

    // 创建知识库结果区域
    if (data.knowledgeBases && data.knowledgeBases.length > 0) {
        const kbSection = document.createElement('div');
        kbSection.className = 'search-result-section mb-8';
        kbSection.id = 'knowledgeBases-results';

        const kbTitle = document.createElement('h3');
        kbTitle.className = 'text-lg font-bold mb-2';
        kbTitle.textContent = '知识库';
        kbSection.appendChild(kbTitle);

        const kbGrid = document.createElement('div');
        kbGrid.className = 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4';

        data.knowledgeBases.forEach(kb => {
            kbGrid.appendChild(createKnowledgeBaseCard(kb));
        });

        kbSection.appendChild(kbGrid);
        container.appendChild(kbSection);
    }

    // 创建文章结果区域
    if (data.articles && data.articles.length > 0) {
        const articleSection = document.createElement('div');
        articleSection.className = 'search-result-section mb-8';
        articleSection.id = 'articles-results';

        const articleTitle = document.createElement('h3');
        articleTitle.className = 'text-lg font-bold mb-2';
        articleTitle.textContent = '文章';
        articleSection.appendChild(articleTitle);

        data.articles.forEach(article => {
            articleSection.appendChild(createArticleItem(article));
        });

        container.appendChild(articleSection);
    }

    // 创建用户结果区域
    if (data.users && data.users.length > 0) {
        const userSection = document.createElement('div');
        userSection.className = 'search-result-section mb-8';
        userSection.id = 'users-results';

        const userTitle = document.createElement('h3');
        userTitle.className = 'text-lg font-bold mb-2';
        userTitle.textContent = '用户';
        userSection.appendChild(userTitle);

        const userList = document.createElement('div');
        userList.className = 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4';

        data.users.forEach(user => {
            userList.appendChild(createUserCard(user));
        });

        userSection.appendChild(userList);
        container.appendChild(userSection);
    }
}

// 创建用户卡片
function createUserCard(user) {
    const card = document.createElement('div');
    card.className = 'user-card bg-white shadow-md rounded p-4 flex items-center';
    card.onclick = () => showUserProfile(user.id);

    // 设置卡片内容
    card.innerHTML = `
    <img src="${user.avatar || 'https://picsum.photos/30/30'}" alt="用户头像" class="rounded-full w-12 h-12 mr-4">
    <div>
      <h4 class="text-md font-bold">${user.username}</h4>
      <p class="text-gray-600 text-sm">关注: ${user.followingCount || 0} | 粉丝: ${user.followerCount || 0}</p>
    </div>
  `;

    return card;
}

// 显示用户个人主页
function showUserProfile(userId) {
    // 这里可以实现跳转到用户个人主页的逻辑
    UIController.showToast('用户个人主页功能正在开发中', 'info');
}

// 显示文章编辑器
function showArticleEditor(articleId = null) {
    if (!currentKnowledgeBaseId) {
        UIController.showToast('请先选择知识库', 'error');
        return;
    }

    // 显示文章编辑器页面
    UIController.showPage('article-editor');

    // 如果有文章ID，表示编辑现有文章
    if (articleId) {
        // 加载文章内容
        UIController.showLoading();

        ApiService.article.getDetail(articleId)
            .then(res => {
                if (res.code === 200 && res.data) {
                    // 填充编辑器
                    document.getElementById('article-title').value = res.data.title;
                    document.getElementById('editor-content').innerHTML = res.data.content;

                    // 设置表单提交处理
                    document.getElementById('article-form').onsubmit = (e) => {
                        e.preventDefault();
                        updateArticle(articleId);
                    };
                } else {
                    UIController.showToast(res.message || '加载文章失败', 'error');
                }
            })
            .catch(err => {
                UIController.showToast(err.message || '加载文章失败', 'error');
            })
            .finally(() => {
                UIController.hideLoading();
            });
    } else {
        // 新建文章，清空编辑器
        document.getElementById('article-title').value = '';
        document.getElementById('editor-content').innerHTML = '';

        // 重置当前编辑的文章ID
        currentEditingArticleId = null;
        // // 设置表单提交处理
        // document.getElementById('article-form').onsubmit = (e) => {
        //     e.preventDefault();
        //     createArticle();
        // };
    }
}

// 创建文章
function createArticle() {
    // 获取表单数据
    const title = document.getElementById('article-title').value;
    const content = document.getElementById('editor-content').innerHTML;

    // 表单验证
    if (!title) {
        UIController.showToast('请输入文章标题', 'error');
        return;
    }

    if (!content) {
        UIController.showToast('请输入文章内容', 'error');
        return;
    }

    // 显示加载状态
    UIController.showLoading();

    // 调用创建文章API
    ApiService.article.create(currentKnowledgeBaseId, title, content)
        .then(res => {
            console.log('准备发送的数据:', currentKnowledgeBaseId, title, content); // 调试日志
            if (res.code === 200) {
                UIController.showToast('创建文章成功', 'success');

                // 返回知识库详情页
                showKnowledgeDetail(currentKnowledgeBaseId);
            } else {
                UIController.showToast(res.message || '创建文章失败', 'error');
            }
        })
        .catch(err => {
            UIController.showToast(err.message || '创建文章失败', 'error');
        })
        .finally(() => {
            UIController.hideLoading();
        });
}

// 更新文章
function updateArticle(articleId) {
    // 获取表单数据
    const title = document.getElementById('article-title').value;
    const content = document.getElementById('editor-content').innerHTML;

    // 表单验证
    if (!title) {
        UIController.showToast('请输入文章标题', 'error');
        return;
    }

    if (!content) {
        UIController.showToast('请输入文章内容', 'error');
        return;
    }

    // 显示加载状态
    UIController.showLoading();

    // 调用更新文章API
    ApiService.article.update(articleId, title, content)
        .then(res => {
            if (res.code === 200) {
                UIController.showToast('更新文章成功', 'success');

                // 返回知识库详情页
                showKnowledgeDetail(currentKnowledgeBaseId);
            } else {
                UIController.showToast(res.message || '更新文章失败', 'error');
            }
        })
        .catch(err => {
            UIController.showToast(err.message || '更新文章失败', 'error');
        })
        .finally(() => {
            UIController.hideLoading();
        });
}

// 取消编辑文章
function cancelArticle() {
    // 确认取消
    UIController.showConfirm('确定要取消编辑吗？未保存的内容将丢失！', () => {
        // 返回知识库详情页
        showKnowledgeDetail(currentKnowledgeBaseId);
    });
}

// 显示文章详情
function showArticleDetail(articleId) {
    console.log("显示文章详情:", articleId);
    // 显示加载状态
    if (UIController && typeof UIController.showLoading === 'function') {
        UIController.showLoading();
    }

    // 请求文章详情
    const xhr = new XMLHttpRequest();
    xhr.open('GET', `/Cloud/article/${articleId}`, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (UIController && typeof UIController.hideLoading === 'function') {
                UIController.hideLoading();
            }

            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                console.log('服务器返回的文章详情数据:', response);
                if (response.code === 200) {
                    // 保存当前文章ID
                    window.currentArticleId = articleId;

                    // 如果是从知识库详情页点击来的，确保记录知识库ID
                    if (window.currentKnowledgeBaseId) {
                        // 已经有知识库ID，不需要额外操作
                    } else if (response.data.knowledgeBaseId) {
                        // 如果文章数据中有知识库ID，记录下来
                        window.currentKnowledgeBaseId = response.data.knowledgeBaseId;
                    }

                    // 显示文章详情页
                    showPage('article-detail');

                    const article = response.data;

                    // 填充文章详情
                    const titleDisplay = document.getElementById('article-title-display');
                    if (titleDisplay) {
                        titleDisplay.textContent = article.title;
                        console.log("显示标题详情:", article.title);
                    } else {
                        console.error('未找到 article-title-display 元素');
                    }

                    const authorDisplay = document.getElementById('article-author-display');
                    if (authorDisplay) {
                        authorDisplay.textContent = article.author || '匿名作者';
                        console.log("显示作者详情:", article.author);
                    } else {
                        console.error('未找到 article-author-display 元素');
                    }

                    const timeDisplay = document.getElementById('article-time-display');
                    if (timeDisplay) {
                        timeDisplay.textContent = new Date(article.createTime || Date.now()).toLocaleString();
                    } else {
                        console.error('未找到 article-time-display 元素');
                    }

                    const contentDisplay = document.getElementById('article-content-display');
                    if (contentDisplay) {
                        contentDisplay.textContent = article.content;
                        console.log("显示文本详情:", article.content);
                    } else {
                        console.error('未找到 article-content-display 元素');
                    }

                    // 更新点赞状态
                    const likeButton = document.getElementById('article-like-button');
                    const likeCount = document.getElementById('article-like-count');

                    if (likeButton && likeCount) {
                        likeButton.setAttribute('data-id', articleId);
                        likeButton.setAttribute('data-liked', article.isLiked ? 'true' : 'false');
                        likeButton.className = article.isLiked ? 'fas fa-thumbs-up like-button liked' : 'far fa-thumbs-up like-button';
                        likeCount.textContent = article.likeCount || 0;
                    }

                    // 更新收藏状态
                    const favoriteButton = document.getElementById('article-favorite-button');
                    if (favoriteButton) {
                        favoriteButton.setAttribute('data-id', articleId);
                        favoriteButton.className = article.isFavorite ? 'fas fa-heart favorite-button' : 'far fa-heart favorite-button';
                    }

                    // 加载评论列表
                    loadComments(articleId);
                } else {
                    alert('获取文章详情失败: ' + response.message);
                }
            } else {
                alert('获取文章详情失败, HTTP状态: ' + xhr.status);
            }
        }
    };
    xhr.send();
}
// 更新点赞状态和数量
function updateLikeStatus(articleId, isLiked, likeCount) {
    const likeButton = document.getElementById('like-button');
    const likeCountElement = document.getElementById('like-count');

    if (!likeButton || !likeCountElement) return;

    // 更新点赞数量
    likeCountElement.textContent = likeCount;

    // 更新点赞状态
    likeButton.dataset.liked = isLiked;

    if (isLiked) {
        likeButton.classList.add('liked');
    } else {
        likeButton.classList.remove('liked');
    }
}

// 显示加载状态
function showLoading(likeButton) {
    likeButton.disabled = true;
    likeButton.classList.add('loading');
}

// 隐藏加载状态
function hideLoading(likeButton) {
    likeButton.disabled = false;
    likeButton.classList.remove('loading');
}

// // 处理点赞错误
// function handleLikeError(likeButton, likeCountElement, isLiked, currentCount) {
//     // 回滚UI更改
//     likeButton.dataset.liked = isLiked;
//     likeButton.classList.toggle('liked', isLiked);
//     likeButton.classList.toggle('fas', isLiked);
//     likeButton.classList.toggle('far', !isLiked);
//     likeCountElement.textContent = currentCount;
//     UIController.showToast('操作失败', 'error');
//     hideLoading(likeButton);
// }

// 切换文章点赞状态
function toggleLike(event) {
    // 获取点赞按钮和计数元素
    const likeButton = event.target.closest('.like-button');
    if (!likeButton) return;

    const articleId = likeButton.getAttribute('data-id');
    const isLiked = likeButton.getAttribute('data-liked') === 'true';
    const likeCount = document.getElementById('article-like-count');
    const currentCount = parseInt(likeCount.textContent || '0');

    // 立即更新UI
    likeButton.setAttribute('data-liked', !isLiked);
    likeButton.className = `fa-thumbs-up ${!isLiked ? 'fas liked' : 'far'} like-button`;
    likeCount.textContent = isLiked ? (currentCount - 1) : (currentCount + 1);

    // 调用API更新点赞状态
    const xhr = new XMLHttpRequest();
    xhr.open('POST', isLiked ? `/Cloud/article/${articleId}/unlike` : `/Cloud/article/${articleId}/like`, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                if (response.code !== 200) {
                    // 回滚UI更改
                    likeButton.setAttribute('data-liked', isLiked);
                    likeButton.className = `fa-thumbs-up ${isLiked ? 'fas liked' : 'far'} like-button`;
                    likeCount.textContent = currentCount;
                    if (UIController && typeof UIController.showToast === 'function') {
                        UIController.showToast('操作失败', 'error');
                    } else {
                        alert('操作失败');
                    }
                }
            } else {
                // 回滚UI更改
                likeButton.setAttribute('data-liked', isLiked);
                likeButton.className = `fa-thumbs-up ${isLiked ? 'fas liked' : 'far'} like-button`;
                likeCount.textContent = currentCount;
                if (UIController && typeof UIController.showToast === 'function') {
                    UIController.showToast('网络错误', 'error');
                } else {
                    alert('网络错误');
                }
            }
        }
    };
    xhr.send();
}

// 切换文章点赞状态
function toggleArticleLike(event) {
    event.stopPropagation();

    const likeButton = document.getElementById('article-like-button');
    const likeCount = document.getElementById('article-like-count');
    const articleId = likeButton.getAttribute('data-id');

    if (!articleId) {
        console.error('未找到文章ID');
        return;
    }

    const isLiked = likeButton.getAttribute('data-liked') === 'true';
    const currentCount = parseInt(likeCount.textContent) || 0;

    // 先更新UI
    if (isLiked) {
        likeButton.classList.remove('fas', 'liked');
        likeButton.classList.add('far');
        likeButton.setAttribute('data-liked', 'false');
        likeCount.textContent = Math.max(0, currentCount - 1);
    } else {
        likeButton.classList.remove('far');
        likeButton.classList.add('fas', 'liked');
        likeButton.setAttribute('data-liked', 'true');
        likeCount.textContent = currentCount + 1;
    }

    // 发送请求
    const xhr = new XMLHttpRequest();
    xhr.open('POST', `/Cloud/article/${isLiked ? 'unlike' : 'like'}/${articleId}`, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status !== 200) {
                // 如果请求失败，回滚UI更改
                if (isLiked) {
                    likeButton.classList.remove('far');
                    likeButton.classList.add('fas', 'liked');
                    likeButton.setAttribute('data-liked', 'true');
                    likeCount.textContent = currentCount;
                } else {
                    likeButton.classList.remove('fas', 'liked');
                    likeButton.classList.add('far');
                    likeButton.setAttribute('data-liked', 'false');
                    likeCount.textContent = currentCount;
                }

                alert('操作失败，请稍后重试');
            }
        }
    };
    xhr.send();
}

// 切换文章收藏状态
function toggleArticleFavorite(event) {
    event.stopPropagation();

    const favoriteButton = document.getElementById('article-favorite-button');
    const articleId = favoriteButton.getAttribute('data-id');

    if (!articleId) {
        console.error('未找到文章ID');
        return;
    }

    const isFavorite = favoriteButton.classList.contains('fas');

    // 先更新UI
    if (isFavorite) {
        favoriteButton.classList.remove('fas');
        favoriteButton.classList.add('far');
        if (UIController && typeof UIController.showToast === 'function') {
            UIController.showToast('已取消收藏', 'info');
        }
    } else {
        favoriteButton.classList.remove('far');
        favoriteButton.classList.add('fas');
        if (UIController && typeof UIController.showToast === 'function') {
            UIController.showToast('已添加收藏', 'success');
        }
    }

    // 发送请求
    const xhr = new XMLHttpRequest();
    xhr.open('POST', `/Cloud/article/${isFavorite ? 'unfavorite' : 'favorite'}/${articleId}`, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status !== 200) {
                // 如果请求失败，回滚UI更改
                if (isFavorite) {
                    favoriteButton.classList.remove('far');
                    favoriteButton.classList.add('fas');
                } else {
                    favoriteButton.classList.remove('fas');
                    favoriteButton.classList.add('far');
                }

                alert('操作失败，请稍后重试');
            }
        }
    };
    xhr.send();
}

// 添加回滚UI的辅助函数
function rollbackLikeUI(likeButton, likeCountElement, isLiked, currentCount) {
    likeButton.setAttribute('data-liked', isLiked);
    likeButton.classList.toggle('liked', isLiked);
    likeButton.classList.toggle('fas', isLiked);
    likeButton.classList.toggle('far', !isLiked);
    likeCountElement.textContent = currentCount;
}

// 处理点赞错误
function handleLikeError(likeButton, likeCountElement, isLiked, currentCount) {
    // 回滚UI更改
    likeButton.dataset.liked = isLiked;
    likeButton.classList.toggle('liked', isLiked);
    likeButton.classList.toggle('fas', isLiked);
    likeButton.classList.toggle('far', !isLiked);
    likeCountElement.textContent = currentCount;
    UIController.showToast('操作失败', 'error');
    hideLoading(likeButton);
}

// // 切换点赞状态
// function toggleLike(articleId) {
//     const likeButton = document.getElementById(`like-button-${articleId}`);
//     const likeCountElement = document.getElementById(`like-count-${articleId}`);
//
//     if (!likeButton || !likeCountElement) return;
//
//     const isLiked = likeButton.dataset.liked === 'true';
//     const currentCount = parseInt(likeCountElement.textContent);
//
//     // 优化：立即更新UI，提升用户体验
//     likeButton.dataset.liked = !isLiked;
//     likeButton.classList.toggle('liked', !isLiked);
//     likeButton.classList.toggle('fas', !isLiked);
//     likeButton.classList.toggle('far', isLiked);
//     likeCountElement.textContent = isLiked ? currentCount - 1 : currentCount + 1;
//
//     // 调用API更新点赞状态
//     ApiService.article[isLiked ? 'unlike' : 'like'](articleId)
//         .then(res => {
//             if (res.code !== 200) {
//                 // 如果API调用失败，回滚UI更改
//                 likeButton.dataset.liked = isLiked;
//                 likeButton.classList.toggle('liked', isLiked);
//                 likeButton.classList.toggle('fas', isLiked);
//                 likeButton.classList.toggle('far', !isLiked);
//                 likeCountElement.textContent = currentCount;
//                 UIController.showToast(res.message || '操作失败', 'error');
//             }
//         })
//         .catch(err => {
//             // 回滚UI更改
//             likeButton.dataset.liked = isLiked;
//             likeButton.classList.toggle('liked', isLiked);
//             likeButton.classList.toggle('fas', isLiked);
//             likeButton.classList.toggle('far', !isLiked);
//             likeCountElement.textContent = currentCount;
//             UIController.showToast(err.message || '操作失败', 'error');
//         });
// }

// 加载评论列表
function loadComments(articleId) {
    const commentsContainer = document.getElementById('comments-container');
    if (!commentsContainer) return;

    // 显示加载中
    commentsContainer.innerHTML = '<div class="text-center p-4">加载评论中...</div>';

    const xhr = new XMLHttpRequest();
    xhr.open('GET', `/Cloud/comment/article/${articleId}`, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.code === 200) {
                        commentsContainer.innerHTML = '';
                        if (!response.data || response.data.length === 0) {
                            commentsContainer.innerHTML = '<div class="text-center text-gray-500 p-4">暂无评论，快来发表第一条评论吧！</div>';
                            console.log('评论列表加载完成');
                            return;
                        }
                        // 渲染评论列表
                        response.data.forEach(comment => {
                            commentsContainer.appendChild(createCommentItem(comment));
                        });
                        console.log('评论列表加载完成');
                    } else {
                        commentsContainer.innerHTML = '<div class="text-center text-red-500 p-4">加载评论失败: ' + response.message + '</div>';
                    }
                } catch (e) {
                    commentsContainer.innerHTML = '<div class="text-center text-red-500 p-4">解析评论数据失败</div>';
                    console.error('解析评论数据失败:', e);
                }
            } else {
                alert('获取评论列表失败: ' + response.message);
            }
        }
    };
    xhr.send();
}

// 创建评论项
function createCommentItem(comment) {
    const commentDiv = document.createElement('div');
    commentDiv.className = 'bg-gray-50 rounded p-4 mb-4';
    commentDiv.setAttribute('data-id', comment.id);

    // 格式化时间
    const createTime = new Date(comment.createTime || Date.now()).toLocaleString();

    commentDiv.innerHTML = `
        <div class="flex items-start">
            <img src="${comment.userAvatar || 'https://picsum.photos/30/30'}" alt="用户头像" class="w-10 h-10 rounded-full mr-3">
            <div class="flex-1">
                <div class="flex items-center">
                    <h4 class="font-bold">${comment.userName || '匿名用户'}</h4>
                    <span class="text-gray-500 text-sm ml-2">${createTime}</span>
                </div>
                <p class="my-2">${comment.content}</p>
                <button class="text-blue-500 text-sm" onclick="showReplyForm(${comment.id})">回复</button>
                
                <div id="reply-form-${comment.id}" class="hidden mt-3">
                    <textarea class="w-full border rounded p-2 mb-2" placeholder="写下你的回复..."></textarea>
                    <div class="flex justify-end space-x-2">
                        <button class="px-4 py-1 bg-gray-300 rounded" onclick="hideReplyForm(${comment.id})">取消</button>
                        <button class="px-4 py-1 bg-blue-500 text-white rounded" onclick="submitReply(${comment.id})">回复</button>
                    </div>
                </div>
            </div>
        </div>
    `;

    // 如果有子评论，递归添加
    if (comment.children && comment.children.length > 0) {
        const childrenContainer = document.createElement('div');
        childrenContainer.className = 'ml-12 mt-3';

        comment.children.forEach(childComment => {
            childrenContainer.appendChild(createCommentItem(childComment));
        });

        commentDiv.appendChild(childrenContainer);
    }

    return commentDiv;
}

// 渲染评论树形结构
function renderCommentTree(container, comments, parentId = null) {
    // 筛选当前层级的评论
    const currentLevelComments = comments.filter(comment => comment.parentId === parentId);

    // 如果没有评论，返回
    if (currentLevelComments.length === 0) return;

    // 创建评论列表容器
    const list = parentId === null ? container : document.createElement('div');
    if (parentId !== null) {
        list.className = 'pl-8 mt-2';
    }

    // 遍历评论
    currentLevelComments.forEach(comment => {
        // 创建评论项
        const item = document.createElement('div');
        item.className = 'comment-item bg-gray-50 p-3 rounded mb-3';

        // 格式化时间
        const createTime = new Date(comment.createTime).toLocaleString();

        // 设置评论内容
        item.innerHTML = `
      <div class="flex items-start mb-2">
        <img src="${comment.userAvatar || 'https://picsum.photos/30/30'}" alt="用户头像" class="rounded-full w-8 h-8 mr-2">
        <div>
          <div class="flex items-center">
            <h4 class="text-md font-bold">${comment.userName}</h4>
            <span class="text-gray-500 text-xs ml-2">${createTime}</span>
          </div>
          <p class="text-gray-700">${comment.content}</p>
        </div>
      </div>
      <div class="flex justify-end">
        <button class="text-sm text-blue-500" onclick="showReplyForm(${comment.id})">回复</button>
      </div>
      <div id="reply-form-${comment.id}" class="reply-form hidden mt-2">
        <textarea class="w-full p-2 border rounded" placeholder="写下你的回复..."></textarea>
        <div class="flex justify-end mt-2">
          <button class="bg-gray-300 text-gray-700 px-3 py-1 rounded mr-2" onclick="hideReplyForm(${comment.id})">取消</button>
          <button class="bg-blue-500 text-white px-3 py-1 rounded" onclick="submitReply(${comment.id})">回复</button>
        </div>
      </div>
    `;

        // 添加到列表容器
        list.appendChild(item);

        // 递归渲染子评论
        renderCommentTree(item, comments, comment.id);
    });

    // 如果不是根容器，添加到父节点
    if (parentId !== null) {
        container.appendChild(list);
    }
}

// 显示回复表单
function showReplyForm(commentId) {
    const replyForm = document.getElementById(`reply-form-${commentId}`);
    if (replyForm) {
        replyForm.classList.remove('hidden');
    }
}

// 隐藏回复表单
function hideReplyForm(commentId) {
    const replyForm = document.getElementById(`reply-form-${commentId}`);
    if (replyForm) {
        replyForm.classList.add('hidden');
    }
}

// 提交回复
function submitReply(commentId) {
    const replyForm = document.getElementById(`reply-form-${commentId}`);
    if (!replyForm) return;

    const textarea = replyForm.querySelector('textarea');
    if (!textarea) return;

    const content = textarea.value.trim();
    if (!content) {
        alert('请输入回复内容');
        return;
    }

    const articleId = window.currentArticleId;
    if (!articleId) {
        alert('未找到文章ID');
        return;
    }

    // 发送请求
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/Cloud/comment', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.code === 200) {
                        // 清空输入框并隐藏回复表单
                        textarea.value = '';
                        hideReplyForm(commentId);

                        // 重新加载评论列表
                        loadComments(articleId);

                        if (UIController && typeof UIController.showToast === 'function') {
                            UIController.showToast('回复成功', 'success');
                        } else {
                            alert('回复成功');
                        }
                    } else {
                        alert('发表回复失败: ' + response.message);
                    }
                } catch (e) {
                    alert('解析响应失败');
                    console.error('解析响应失败:', e);
                }
            } else {
                alert('发表回复失败');
            }
        }
    };

    const data = JSON.stringify({
        articleId: articleId,
        parentId: commentId,
        content: content
    });

    xhr.send(data);
}

// 提交评论
function submitComment() {
    const commentInput = document.getElementById('comment-input');
    if (!commentInput) return;

    const content = commentInput.value.trim();
    if (!content) {
        alert('请输入评论内容');
        return;
    }

    const articleId = window.currentArticleId;
    if (!articleId) {
        alert('未找到文章ID');
        return;
    }

    // 发送请求
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/Cloud/comment', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.code === 200) {
                        // 清空输入框
                        commentInput.value = '';

                        // 重新加载评论列表
                        loadComments(articleId);

                        if (UIController && typeof UIController.showToast === 'function') {
                            UIController.showToast('评论成功', 'success');
                        } else {
                            alert('评论成功');
                        }
                    } else {
                        alert('发表评论失败: ' + response.message);
                    }
                } catch (e) {
                    alert('解析响应失败');
                    console.error('解析响应失败:', e);
                }
            } else {
                alert('发表评论失败');
            }
        }
    };

    const data = JSON.stringify({
        articleId: articleId,
        parentId: null,
        content: content
    });

    xhr.send(data);
}

// 获取当前文章ID
function getCurrentArticleId() {
    // 从URL中获取文章ID
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get('articleId');
}

// 记录浏览历史
function recordBrowseHistory(articleId) {
    // 简单实现：仅在控制台记录
    console.log('记录浏览历史，文章ID:', articleId);

    // 实际实现可以调用相应的API
    // const xhr = new XMLHttpRequest();
    // xhr.open('POST', '/Cloud/browse-history', true);
    // xhr.setRequestHeader('Content-Type', 'application/json');
    // xhr.send(JSON.stringify({ articleId: articleId }));
}

// 加载浏览记录
function loadBrowseHistory() {
    ApiService.browseHistory.getList()
        .then(res => {
            if (res.code === 200 && res.data) {
                // 获取浏览记录容器
                const container = document.getElementById('browse-history');
                container.innerHTML = '';

                // 如果没有浏览记录，显示提示
                if (res.data.length === 0) {
                    container.innerHTML = '<div class="text-center text-gray-500 p-4">暂无浏览记录</div>';
                    return;
                }

                // 渲染浏览记录
                res.data.forEach(history => {
                    const item = document.createElement('div');
                    item.className = 'browse-history-item p-2 hover:bg-gray-100 rounded flex justify-between';

                    // 格式化时间
                    const browseTime = new Date(history.browseTime).toLocaleString();

                    // 设置列表项内容
                    item.innerHTML = `
            <div class="flex-1 cursor-pointer" onclick="showArticleDetail(${history.articleId})">
              <h4 class="text-md font-bold">${history.articleTitle}</h4>
              <p class="text-gray-600 text-sm">浏览时间：${browseTime}</p>
            </div>
            <button class="text-red-500" onclick="deleteBrowseHistory(${history.id}, event)">
              <i class="fas fa-trash"></i>
            </button>
          `;

                    container.appendChild(item);
                });

                // 添加清空按钮
                const clearButton = document.createElement('button');
                clearButton.className = 'bg-red-500 text-white px-4 py-2 rounded mt-4';
                clearButton.textContent = '清空浏览记录';
                clearButton.onclick = clearBrowseHistory;
                container.appendChild(clearButton);
            } else {
                UIController.showToast(res.message || '加载浏览记录失败', 'error');
            }
        })
        .catch(err => {
            UIController.showToast(err.message || '加载浏览记录失败', 'error');
        });
}

// 删除单条浏览记录
function deleteBrowseHistory(id, event) {
    // 阻止事件冒泡
    event.stopPropagation();

    // 确认删除
    UIController.showConfirm('确定要删除此条浏览记录吗？', () => {
        ApiService.browseHistory.delete(id)
            .then(res => {
                if (res.code === 200) {
                    UIController.showToast('删除成功', 'success');

                    // 重新加载浏览记录
                    loadBrowseHistory();
                } else {
                    UIController.showToast(res.message || '删除失败', 'error');
                }
            })
            .catch(err => {
                UIController.showToast(err.message || '删除失败', 'error');
            });
    });
}

// 格式化文本编辑器内容
function applyFormat(command) {
    document.execCommand(command, false, null);
    document.getElementById('editor-content').focus();
}

// 上传图片
function uploadImage() {
    // 创建文件选择器
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';

    // 绑定文件选择事件
    input.onchange = function() {
        if (this.files && this.files[0]) {
            const file = this.files[0];

            // 创建FormData对象
            const formData = new FormData();
            formData.append('file', file);

            // 显示加载状态
            UIController.showLoading();

            // 上传图片
            fetch('/upload/image', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        // 插入图片
                        document.execCommand('insertImage', false, data.data.url);
                        UIController.showToast('图片上传成功', 'success');
                    } else {
                        UIController.showToast(data.message || '图片上传失败', 'error');
                    }
                })
                .catch(err => {
                    UIController.showToast('图片上传失败', 'error');
                    console.error('图片上传失败:', err);
                })
                .finally(() => {
                    UIController.hideLoading();
                });
        }
    };

    // 触发文件选择
    input.click();
}

// 加载用户信息
function loadUserInfo() {
    ApiService.auth.getCurrentUser()
        .then(res => {
            if (res.code === 200 && res.data) {
                // 显示用户信息
                document.querySelectorAll('.user-avatar').forEach(avatar => {
                    avatar.src = res.data.avatar || 'https://picsum.photos/30/30';
                });

                document.querySelectorAll('.user-name').forEach(name => {
                    name.textContent = res.data.username;
                });

                // 存储用户信息
                localStorage.setItem('currentUser', JSON.stringify(res.data));
            }
        })
        .catch(err => {
            console.error('加载用户信息失败:', err);
        });
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            func.apply(context, args);
        }, wait);
    };
}



// 导出模块
window.KnowledgeManager = {
    initKnowledgePage,
    loadRecentKnowledgeBases,
    loadRecommendedKnowledgeBases,
    loadRecentArticles,
    sortArticles,
    showKnowledgeDetail,
    createKnowledgeBase,
    updateKnowledgeBase,
    deleteKnowledgeBase,
    showArticleEditor,
    createArticle,
    updateArticle,
    cancelArticle,
    showArticleDetail,
    toggleLike,
    submitComment,
    loadBrowseHistory,
    search
};
// DOM Ready event handler
document.addEventListener('DOMContentLoaded', function() {
    console.log("DOM加载完成，初始化UI控制器");

    // !!!
    // // Check if user is authenticated
    // const token = localStorage.getItem('token') || sessionStorage.getItem('token');
    // if (!token) {
    //     console.log("User not authenticated, redirecting to login page");
    //     // Uncomment the next line to enable redirection
    //     // window.location.href = 'login.html';
    //
    //     // For now, just show a message instead of redirecting
    //     alert("未登录或会话已过期，请重新登录222");
    // }
    // Make functions globally available
    window.showPage = showPage;
    window.toggleUserMenu = toggleUserMenu;
    window.backToKnowledgeDetail = backToKnowledgeDetail;
    window.showCreateKnowledgeBaseModal = showCreateKnowledgeBaseModal;
    window.hideCreateKnowledgeBaseModal = hideCreateKnowledgeBaseModal;
    window.createKnowledgeBase = createKnowledgeBase;
    window.showKnowledgeDetail = showKnowledgeDetail;
    window.showArticleEditor = showArticleEditor;
    window.applyFormat = applyFormat;
    window.uploadImage = uploadImage;
    window.saveArticle = saveArticle;
    window.cancelArticle = cancelArticle;
    window.toggleLike = toggleLike;
    window.submitComment = submitComment;
    window.toggleFavorite = toggleFavorite;
    window.search = search;
    window.toggleArticleLike = toggleArticleLike;
    window.toggleArticleFavorite = toggleArticleFavorite;
    window.showReplyForm = showReplyForm;
    window.hideReplyForm = hideReplyForm;
    window.submitReply = submitReply;
    window.submitComment = submitComment;
    window.showArticleDetail = showArticleDetail;
    // Initialize any needed functionality
    // Uncomment any of these that you need to run on page load
    loadKnowledgeBases();
    getRecentArticles();
    getArticlesByPage(1);

    // 使用UIController隐藏加载指示器
    if (UIController && typeof UIController.hideLoading === 'function') {
        UIController.hideLoading();
    } else {
        // 备用方案
        const loadingElement = document.getElementById('loading');
        if (loadingElement) {
            loadingElement.classList.add('hidden');
        }
    }

    console.log("Initialization complete");
});